package cn.stylefeng.guns.modular.business.frequency.transport.controller;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.custom.enums.ReturnCode;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickCarExcludeDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSubBase;
import cn.stylefeng.guns.modular.business.frequency.siterelation.entity.SiteRelation;
import cn.stylefeng.guns.modular.business.frequency.siterelation.service.SiteRelationService;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.entity.Transport;
import cn.stylefeng.guns.modular.business.frequency.transport.model.param.TransportDTO;
import cn.stylefeng.guns.modular.business.frequency.transport.model.result.*;
import cn.stylefeng.guns.modular.business.frequency.transport.service.TransportService;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.entity.TransportLevel;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.mapper.TransportLevelMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.EasyExcelUtil;
import cn.stylefeng.guns.sys.modular.role.RoleConstant;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author jzy
 * @Date 2020/10/19 0019
 **/
@Api(tags = "发运管理")
@RestController
@RequestMapping("/api/transport")
public class TransportController {

    @Resource
    private TransportService transportService;
    @Resource
    private SysSiteMapper siteMapper;
    @Resource
    private TransportLevelMapper transportLevelMapper;
    @Resource
    private BusinessUtil businessUtil;

/*
    @AnonymousGetMapping("/data-fix")
    public ResponseData dataFix() {
        transportService.dataFix();
        return ResponseData.success();
    }
*/

    @ApiOperation(value = "待发运订单分页列表")
    @GetMapping("/wait")
    @PreAuthorize("@el.check('transport:list')")
    public ResponseData getWaitTransportListPage(OrderDTO orderDTO) {

        // 数据权限
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        // 添加网点部角色数据范围
        getWaitTransportQueryParam(orderDTO);
        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        Page page = transportService.getWaitTransportOrderList(orderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(page, orderDTO));
    }

    @Autowired
    private SiteRelationService siteRelationService;
    @Autowired
    private SysUserService sysUserService;

    private void getWaitTransportQueryParam(OrderDTO orderDTO) {
        List<String> roleCodeList = sysUserService.getRoleCodeListByUserId(LoginContextHolder.me().getSysLoginUserId());
        //网点部可以看到自己服务城市的订单，即订单的出发地在自己网点的服务城市内，还有自己创建的订单，所以这里分配全部数据权限
        if (roleCodeList.contains(RoleConstant.网点部角色)) {
            SiteRelation siteRelation = siteRelationService.getOne(new LambdaQueryWrapper<SiteRelation>().eq(SiteRelation::getUserId, LoginContextHolder.me().getSysLoginUserId()));
            if (siteRelation != null && siteRelation.getSiteId() != null) {
                List<String> chargeCityList = siteMapper.getServiceCodes(siteRelation.getSiteId().toString());
                orderDTO.setStartCodeList(chargeCityList);
                orderDTO.setDispatcherId(LoginContextHolder.me().getSysLoginUserId().toString());
                Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
                List<Long> siteUserIds = businessUtil.getEmpByOrgId(sysLoginUserOrgId);
                orderDTO.setDataList(siteUserIds);
            }
            if(orderDTO.getStartCodeList()==null){
                orderDTO.setStartCodeList(new ArrayList<>());
            }
            orderDTO.getStartCodeList().add("-1");
        }
    }

    private void getFinishTransportQueryParam(TransportDTO transportDTO) {
        List<String> roleCodeList = sysUserService.getRoleCodeListByUserId(LoginContextHolder.me().getSysLoginUserId());
        //网点部可以看到自己服务城市的订单，即订单的出发地在自己网点的服务城市内，还有自己创建的订单，所以这里分配全部数据权限
        if (roleCodeList.contains(RoleConstant.网点部角色)) {
            Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
            List<Long> siteUserIds = businessUtil.getEmpByOrgId(sysLoginUserOrgId);
            transportDTO.setDataList(siteUserIds);
        }
        if (StringUtils.isNotBlank(transportDTO.getKey())) {
            if (transportDTO.getKey().startsWith("Y")) {
                transportDTO.setTransportNo(transportDTO.getKey());
            } else if (transportDTO.getKey().startsWith("D")) {
                transportDTO.setOrderSubNo(transportDTO.getKey());
            } else {
                transportDTO.setVin(transportDTO.getKey());
            }
        }
    }

    @ApiOperation(value = "待发运出发地目的地筛选列表")
    @GetMapping("/sd-codes")
    public ResponseData getStartCodeAndDestinationCode() {
        OrderDTO orderDTO = new OrderDTO();
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        Map<String, List<String>> map = transportService.getStartCodeAndDestinationCode(orderDTO);
        return ResponseData.andaSuccess(map);
    }


    /**
     * 发运记录
     */
    @ApiOperation(value = "已发运列表")
    @GetMapping("/finish")
    @PreAuthorize("@el.check('transport:list')")
    public ResponseData getFinishTransportList(TransportDTO transportDTO) {
        // 排序
        if (StringUtils.isBlank(transportDTO.getColumn())) {
            transportDTO.setColumn("t.create_time");
        }
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        transportDTO.setDataList(empByOrgList);
        getFinishTransportQueryParam(transportDTO);
        Page<TransportPageVO> list = transportService.getFinishTransportList(transportDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, transportDTO));
    }

    @ApiOperation(value = "发运记录导出")
    @GetMapping("/finish/export")
    public void export(HttpServletResponse response, TransportDTO transportDTO) throws Exception {
        // 排序
        getFinishTransportQueryParam(transportDTO);
        List<TransportExportVO> list = transportService.getFinishTransportList2(transportDTO);
        EasyExcelUtil.export2Web(response, "发运记录数据", "sheet1",
                TransportExportVO.class, list);
    }

    @ApiOperation(value = "签收装车运单列表")
    @GetMapping("/sign-to-transport")
    @PreAuthorize("@el.check('transport:list')")
    public ResponseData getSignedTransportList(TransportDTO transportDTO) {
        // 只有网点可以签收装车
        Long siteId = siteMapper.getSiteIdByUser(LoginContextHolder.me().getSysLoginUserId());
        if (siteId != null) {
            transportDTO.setSiteId(siteId);
        } else {
            throw new CustomException("您没有签收装车的权限！");
        }

        if (StringUtils.isBlank(transportDTO.getColumn())) {
            transportDTO.setColumn("t.create_time");
        }
        Page<TransportPageVO> list = transportService.getSignedTransportList(transportDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, transportDTO));
    }

    /*    *
     * @param id    运单ID
     * @param scene 1.运单详情 2.在途运单详情，过滤掉已到达的分段
     * @return*/

    @ApiOperation(value = "发运单详情")
    @GetMapping("/{id}")
    public ResponseData getTransportDetail(@PathVariable String id,
                                           @RequestParam(value = "scene", required = false, defaultValue = "1") Integer scene) {
        TransportDTO transportDTO = new TransportDTO();
        // 数据权限
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        transportDTO.setDataList(empByOrgList);
        PkgTransport transport = transportService.getTransportDetail(id, scene, transportDTO);
        return ResponseData.andaSuccess(transport);
    }

    /*   *
     * @param levelId 运单分段ID
     * @return
     */
    @ApiOperation(value = "发运单分段详情")
    @GetMapping("/level/{levelId}")
    public ResponseData getTransportLevelDetail(@PathVariable String levelId) {
        PkgTransportLevel level = transportService.getTransportLevelDetail(levelId);
        return ResponseData.andaSuccess(level);
    }

    @ApiOperation(value = "运单简易详情")
    @GetMapping("/simple/{id}")
    public ResponseData getTransportSimpleDetail(@PathVariable String id) {
        Transport transport = transportService.getById(id);
        return ResponseData.andaSuccess(transport);
    }

    @ApiOperation(value = "运单详情（按订单展开）")
    @GetMapping("/expand/{id}")
    public ResponseData getTransportExpandDetail(@PathVariable String id) {
        TransportDTO transportDTO = new TransportDTO();
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        transportDTO.setDataList(empByOrgList);
        List<TransportExpandVO> list = transportService.getTransportExpandDetail(id, transportDTO);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "发运单编辑详情")
    @GetMapping("/update/{id}")
    public ResponseData getTransportUpdateDetail(@PathVariable String id) {
        TransportDTO transportDTO = new TransportDTO();
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        transportDTO.setDataList(empByOrgList);
        transportDTO.setTransportId(id);
        TransportVO transportVO = transportService.getTransportVODetail(transportDTO);


        List<TransportLevel> transportLevelList = transportLevelMapper.selectGroupByCreateUser(id);
        if (transportLevelList.size() == 1) {
            transportVO.setUpdateType(0);
        } else {
            if (LoginContextHolder.me().getSysLoginUserId().equals(transportLevelList.get(0).getCreateUser())) {
                transportVO.setUpdateType(1);
            } else {
                transportVO.setUpdateType(2);
            }
        }
        return ResponseData.andaSuccess(ReturnCode.RETURN_SUCCESS.code, transportVO);
    }

    @ApiOperation(value = "发运单子订单信息列表")
    @GetMapping("/sub-order/{transportId}")
    public ResponseData getTransportOrderList(@PathVariable String transportId) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setTransportId(transportId);
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        List<PkgTransportOrderDetail> list = transportService.getTransportOrderDetail(orderDTO);
        return ResponseData.andaSuccess(ReturnCode.RETURN_SUCCESS.code, list);
    }

    @ApiOperation(value = "添加待发运弹框筛选")
    @GetMapping("/wait-exclude")
    public ResponseData getWaitTransportExclude(PickCarExcludeDTO pickCarExcludeDTO) {
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        pickCarExcludeDTO.setDataList(empByOrgList);
        Page<PkgOrderSubBase> list = transportService.getWaitTransportExcludeList(pickCarExcludeDTO);
        return ResponseData.andaSuccess(ReturnCode.RETURN_SUCCESS.code, list);
    }


    @ApiOperation(value = "批量指派发运")
    @PostMapping
    @PreAuthorize("@el.check('transport:add')")
    public ResponseData transport(@Validated @RequestBody TransportVO transportVO) {
        StringBuilder errorMsg = new StringBuilder();
//        校验发运参数
        if (!transportService.checkTransportAdd(transportVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        transportService.transport(transportVO);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "回退发运")
    @GetMapping("/returnTransport/{orderId}")
    @PreAuthorize("@el.check('transport:add')")
    public ResponseData returnTransport(@PathVariable Long orderId) {
        transportService.returnTransport(orderId);
        return ResponseData.andaSuccess();
    }

    //@NoRepeatSubmit
    @ApiOperation(value = "发运修改")
    @PostMapping("/update")
    @PreAuthorize("@el.check('transport:add')")
    public ResponseData transportUpdate(@Validated @RequestBody TransportVO transportVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!transportService.checkTransportUpdate(transportVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        transportService.updateTran(transportVO);
        return ResponseData.andaSuccess();
    }


    //@NoRepeatSubmit
    @ApiOperation(value = "运单取消")
    @PostMapping("/cancel/{id}")
    @PreAuthorize("@el.check('transport:add')")
    public ResponseData transportCancel(@PathVariable String id) {

        StringBuilder errorMsg = new StringBuilder();
        if (!transportService.checkTransportCancel(id, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        // 取消
        transportService.cancel(id);
        return ResponseData.andaSuccess();
    }


    //@NoRepeatSubmit
    @ApiOperation(value = "签收装车")
    @PostMapping("/reserved-transport")
    public ResponseData reservedTransport(@RequestBody TransportVO transportVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!transportService.checkReservedTransport(transportVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        transportService.reservedTransport(transportVO);
        return ResponseData.andaSuccess();
    }


    @ApiOperation(value = "订单发运信息")
    @GetMapping("/order/{orderId}")
    public ResponseData getOrderTransportDetail(@PathVariable String orderId) {
        List<PkgTransport> list = transportService.getOrderTransportDetail(orderId);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "司机APP结算人指派司机")
    @PostMapping("/driver-app/assign")
    public ResponseData driverAssign(@RequestBody Transport transport) {
        StringBuilder errorMsg = new StringBuilder();
        if (!transportService.checkMultiDriverAssign(transport, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        transportService.assignDriver(transport);
        return ResponseData.andaSuccess("指派司机成功");
    }

    @ApiOperation(value = "运单订单明细导出")
    @GetMapping("/export/{levelId}")
    public void exportTransportOrderDetail(HttpServletResponse response, @PathVariable String levelId) throws Exception {
        EasyExcelUtil.export2Web(response, "运单订单明细", "sheet1",
                TransportOrderExport.class, transportService.getTransportOrderExport(levelId));
    }
}
